package com.blockmeta.bbs.businesslibrary.util;

import android.content.Context;
import android.util.Log;

import com.alibaba.sdk.android.oss.ClientConfiguration;
import com.alibaba.sdk.android.oss.ClientException;
import com.alibaba.sdk.android.oss.OSS;
import com.alibaba.sdk.android.oss.OSSClient;
import com.alibaba.sdk.android.oss.ServiceException;
import com.alibaba.sdk.android.oss.callback.OSSCompletedCallback;
import com.alibaba.sdk.android.oss.callback.OSSProgressCallback;
import com.alibaba.sdk.android.oss.common.OSSLog;
import com.alibaba.sdk.android.oss.common.auth.OSSCredentialProvider;
import com.alibaba.sdk.android.oss.common.auth.OSSStsTokenCredentialProvider;
import com.alibaba.sdk.android.oss.internal.OSSAsyncTask;
import com.alibaba.sdk.android.oss.model.PutObjectRequest;
import com.alibaba.sdk.android.oss.model.PutObjectResult;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.StringUtils;
import com.blockmeta.bbs.baselibrary.net.Host;
import com.blockmeta.bbs.baselibrary.net.callback.Callback;
import com.blockmeta.bbs.baselibrary.net.callback.FileUploadCallBack;
import com.blockmeta.bbs.baselibrary.utils.gson.GsonUtil;
import com.blockmeta.bbs.baselibrary.utils.loading.ProgressBarUtil;
import com.blockmeta.bbs.businesslibrary.net.okhttp.OKHttpGetReq;
import com.blockmeta.bbs.businesslibrary.net.pojo.BaseImResponse;
import com.google.gson.reflect.TypeToken;

import java.io.File;
import java.lang.reflect.Type;

import static com.blockmeta.bbs.baselibrary.utils.OpenFileUtil.getExtensionName;

/**
 * Created by author on 2019/4/4.
 */
public class Update2QiniuCloud {

    public static final String UpdateOSSHost = Host.MAIN_URL + "/account/osstoken";

    public static void postFileToNet(final Context mContext, String ossDir, final String localFilePath, final FileUploadCallBack responseCallBack) {
        long currentTimeMillis = System.currentTimeMillis();
        //获取上传的文件名称
        String fileExt = getExtensionName(localFilePath);
        final String fileRemoteDir = StringUtils.isEmpty(ossDir) ? "im/" : ossDir + "/";
        final String fileName = fileRemoteDir + currentTimeMillis + AccountHelper.getUid() + "." + fileExt;

        OKHttpGetReq okHttpGetReq = new OKHttpGetReq(mContext, UpdateOSSHost);
        okHttpGetReq.getDataWithUid(new Callback() {

            @Override
            public void onError(String resp) {
                LogUtils.d("author" + "postFileToNet onError" + resp);
                ProgressBarUtil.dismissProgress(mContext);
                if (responseCallBack != null) {
                    responseCallBack.fail("get token fail");
                }
            }

            @Override
            public void onResponse(String resp, int id) {
                postFileToQiniu(mContext, new File(localFilePath), resp, fileName, responseCallBack);
            }
        });


    }

    private static void postFileToQiniu(final Context mContext, File file, String json, final String remoteFileName, final FileUploadCallBack responseCallBack) {
        String endpoint = "http://oss-cn-hangzhou.aliyuncs.com";

//if null , default will be init
        ClientConfiguration conf = new ClientConfiguration();
        conf.setConnectionTimeout(15 * 1000); // connction time out default 15s
        conf.setSocketTimeout(15 * 1000); // socket timeout，default 15s
        conf.setMaxConcurrentRequest(5); // synchronous request number，default 5
        conf.setMaxErrorRetry(2); // retry，default 2
        OSSLog.enableLog(); //write local log file ,path is SDCard_path\OSSLog\logs.csv

        Type type = new TypeToken<BaseImResponse<OSSCredential>>() {
        }.getType();
        BaseImResponse<OSSCredential> data = GsonUtil.buildGson().fromJson(json, type);
        if (data == null) {
            return;
        }
        OSSCredential credential = data.data;
        if (credential == null) {
            return;
        }

        OSSCredentialProvider credentialProvider = new OSSStsTokenCredentialProvider(credential.accessKeyId, credential.accessKeySecret, credential.securityToken);

        OSS oss = new OSSClient(mContext, endpoint, credentialProvider, conf);
// Construct an upload request
        PutObjectRequest put = new PutObjectRequest("quhui123", remoteFileName, file.getPath());

// You can set progress callback during asynchronous upload
        put.setProgressCallback(new OSSProgressCallback<PutObjectRequest>() {
            @Override
            public void onProgress(PutObjectRequest request, long currentSize, long totalSize) {
                Log.d("PutObject", "currentSize: " + currentSize + " totalSize: " + totalSize);
                double progress = currentSize * 1.0 / totalSize;
                LogUtils.d("author" + "upload progress" + progress);
                responseCallBack.progress((int) (progress * 100));
            }
        });

        OSSAsyncTask task = oss.asyncPutObject(put, new OSSCompletedCallback<PutObjectRequest, PutObjectResult>() {
            @Override
            public void onSuccess(PutObjectRequest request, PutObjectResult result) {
                Log.d("PutObject", "UploadSuccess");
                //                        Bitmap bitmap = BitmapFactory.decodeFile(compressPath);
//                        JSONObject jsonObject = new JSONObject(response);
//                        String imgUrl = (String) jsonObject.get("key");
                responseCallBack.success("https://quhui123.oss-cn-hangzhou.aliyuncs.com/" + request.getObjectKey());
                LogUtils.i("author" + result.toString());
            }

            @Override
            public void onFailure(PutObjectRequest request, ClientException clientExcepion, ServiceException serviceException) {
                // Request exception
                if (clientExcepion != null) {
                    // Local exception, such as a network exception
                    clientExcepion.printStackTrace();
                }
                if (serviceException != null) {
                    // Service exception
                    Log.e("ErrorCode", serviceException.getErrorCode());
                    Log.e("RequestId", serviceException.getRequestId());
                    Log.e("HostId", serviceException.getHostId());
                    Log.e("RawMessage", serviceException.getRawMessage());
                }
            }
        });
    }

}
